//
//  ILGLoginManager.m
//  GameDemo
//
//  Created by Happy on 1/16/17.
//  Copyright © 2017 Happy. All rights reserved.
//

#import "ILGLoginManager.h"
#import "ILGThirdDelegate.h"
#import "ILGLocalData.h"

typedef void(^ILGLoginCallBackType)(NSError *error, NSDictionary *result);

@interface ILGLoginManager () {
    
}
@property (nonatomic, copy) ILGLoginCallBackType callBack;
@end


@implementation ILGLoginManager

static ILGLoginManager *_manager;
+ (instancetype)sharedInstance {
    if (!_manager) {
        _manager = [[ILGLoginManager alloc] init];
        
        [ILGThirdDelegate sharedInstance].loginCallback = ^(NSError *error, NSDictionary *result, ILGThirdType loginType) {
            error ? _manager.callBack(error, nil):_manager.callBack(nil, result);
        };
        
    }
    
    return _manager;
}

- (void)loginInWeiXin:(void(^)(NSError *error, NSDictionary *result))callback {
#ifdef ILGWXSDKIncluded
    if (![ILGThirdDelegate isWXAppInstalled]) {
        NSError *noInstallError = [NSError errorWithDomain:@"com.zbsdk.login" code:-2 userInfo:@{NSLocalizedDescriptionKey:@"您还没有安装微信客户端"}];
        callback(noInstallError, nil);
        return;
    }
    if ([ILGThirdDelegate sharedInstance].wxAppId.length == 0) {
        NSError *weiXinError = [NSError errorWithDomain:@"com.zbsdk.login" code:-1 userInfo:@{NSLocalizedDescriptionKey:@"缺少参数微信appid"}];
        callback(weiXinError, nil);
        return;
    }
    _callBack = callback;
    
    
    SendAuthReq* req =[[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"6d4647b70fdf8592c7580218ffde00be" ;
    
    [WXApi sendReq:req];
    
#else
    NSLog(@"ILGSDK 微信登录功能暂未开发");
    
#endif
}

- (void)loginInQQ {
//    NSArray *permissions =  [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, kOPEN_PERMISSION_ADD_SHARE,nil];
//    [[ILGThirdDelegate sharedInstance].tencentOAuth authorize:permissions];
}

// @{@"facebookId":@"在facebook后台申请的appid", @"nickName":@"facebook账户昵称", @"icon":@"facebook账户头像", @"sex":@"性别，1表示男，2表示女"}
- (void)loginInFacebook:(void(^)(NSError *error, NSDictionary *dic))callback {
#ifdef ILGFacebookSDKIncluded
    [NIMProgressHUD dismiss];
    
    FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
    [loginManager logInWithReadPermissions: @[@"public_profile", @"email"] fromViewController:nil handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

         if (error) {
             callback(error, nil);
             
         } else if (result.isCancelled) {
             // 取消了facebook登录
             NSLog(@"facebookLogin 您取消了Facebook登录");
             NSError *customError = [NSError errorWithDomain:@"com.zclogin.error" code:ILGLoginErrorCancel userInfo:@{NSLocalizedDescriptionKey:@"取消"}];
             callback(customError, nil);

         } else {
             NSDictionary *loginParameter = @{@"openId":result.token.userID,
                                                @"accessToken":result.token.tokenString}.mutableCopy;
             NSLog(@"facebook Token appId：%@, token:%@, userId:%@", result.token.appID, result.token.tokenString, result.token.userID);
             
             NSMutableDictionary *profileDic = @{@"facebookId":@"",
                                                 @"nickname":@"",
                                                 @"icon":@"",
                                                 @"sex":@""}.mutableCopy;
             if ([FBSDKAccessToken currentAccessToken]) {
                 [[[FBSDKGraphRequest alloc] initWithGraphPath:@"/me" parameters:@{@"fields": @"id, name, gender, picture, email"}]
                  startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
                      if (!error) {
                          NSDictionary *dic = result;
                          NSLog(@"fetched user:%@,%@,%@", dic, [dic objectForKey:@"id"], [dic objectForKey:@"name"]);
                          
                          if(dic[@"id"]) {
                              [profileDic setObject:dic[@"id"] forKey:@"facebookId"];
                          }
                          
                          if ([dic objectForKey:@"name"]) {
                              [profileDic setObject:[dic objectForKey:@"name"] forKey:@"nickName"];
                          }
                          
                          if (dic[@"picture"][@"data"][@"url"]) {
                              [profileDic setObject:dic[@"picture"][@"data"][@"url"] forKey:@"icon"];
                          }
                          
                          if ([dic[@"gender"] isEqualToString:@"male"]) {
                              [profileDic setObject:@"1" forKey:@"sex"];
                          } else {
                              [profileDic setObject:@"2" forKey:@"sex"];
                          }
                      }
        
                  }];
             }
             
//             [ILGPlatformRequestManager requestForFacebookLogin:loginParameter callback:^(NSError *error, NSDictionary *dic) {
//                 if (error) {
//                     callback(error, nil);
//                 } else {
//                     callback(nil, @{@"zcsdkDic":dic, @"facebookDic":profileDic});
//                 }
//             }];
         }
     }];
#else
    NSLog(@"ILGSDK Facebook登录功能暂未开发");
    
#endif
}

@end
